/*
 *  Copyright (c) 2011, StripBandunk and/or its affiliates. All rights reserved.
 * 
 *       http://stripbandunk.com/
 * 
 *  STRIPBANDUNK PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.stripbandunk.tutorial.simpleapp.controller.impl;

import com.stripbandunk.tutorial.simpleapp.controller.UserController;
import com.stripbandunk.tutorial.simpleapp.entity.Group;
import com.stripbandunk.tutorial.simpleapp.entity.User;
import com.stripbandunk.tutorial.simpleapp.error.SimpleAppException;
import com.stripbandunk.tutorial.simpleapp.repository.UserRepository;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Eko Kurniawan Khannedy
 */
@Controller
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = {SimpleAppException.class})
public class UserControllerImpl implements UserController {

    private UserRepository repository;

    @Autowired
    public void setRepository(UserRepository repository) {
        this.repository = repository;
    }

    @Override
    public void processCreate(User user) {
        user.setCreatedDate(new Date());
        user.setLastModifiedDate(new Date());

        repository.save(user);
    }

    @Override
    public void processEdit(User user) {
        user.setLastModifiedDate(new Date());

        repository.save(user);
    }

    @Override
    public void processMoveToGroup(Group group, User... users) {
        for (User user : users) {
            user.setGroup(group);
            user.setLastModifiedDate(new Date());

            repository.save(user);
        }
    }

    @Override
    public void processDelete(User... users) {
        for (User user : users) {
            repository.delete(user);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<User> processLoad() {
        List<User> users = repository.findAll();
        return users;
    }
}
